package cn.wyf.demo.service;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import cn.wyf.demo.model.XmlData;
import cn.wyf.demo.test.SHA1Util;

public abstract class BaseService {

    public String makeXmlData(List<XmlData> head, List<XmlData> body){
        String data = null;
        if (head != null && !head.isEmpty() && body != null && !body.isEmpty()) {
            Document document = DocumentFactory.getInstance().createDocument();
            document.setXMLEncoding("utf-8");
            Element request = DocumentHelper.createElement("request");
            document.setRootElement(request);

            Element eleHead = request.addElement("requestParam");
            for (XmlData pair : head) {
                if (pair.getValue() != null) {
                    Element element = eleHead.addElement(pair.getName());
                    element.setText(pair.getValue());
                }
            }

            Element eleBody = request.addElement("data");
            for (XmlData pair : body) {
                if (pair.getValue() != null) {
                    Element element = eleBody.addElement(pair.getName());
                    element.setText(pair.getValue());
                }
            }
            Element elepagingInfo = request.addElement("pagingInfo");
            document.asXML();
            String sign = calculSign(eleHead.asXML(), eleBody.asXML(), elepagingInfo.asXML());
            Element eleMac = request.addElement("sign");
            eleMac.setText(sign);

            data = document.asXML();
        }
        return data;
    }

    @Autowired
    private SHA1Util sha1Util;

    /**
     * 上送的报文计算签名
     *
     * @param head
     * @param data
     * @param pageinfo
     * @return
     */
    private String calculSign(String head, String data, String pageinfo) {
        String code = "token^5LandiApp";
        StringBuilder signStr = new StringBuilder();
        signStr.append(code).append("|").append(head).append("|").append(data);
        if (pageinfo != null && pageinfo.length() > 0) {
            signStr.append("|").append(pageinfo);
        }
        return sha1Util.encode(signStr.toString());
    }
}